/*
 * @Author: hcluo
 * @Date: 2020-08-30 09:28:53
 * @LastEditors: hcluo
 * @LastEditTime: 2020-09-01 23:10:09
 * @Description:
 */
import React, { useState, useMemo, useRef, useReducer } from 'react';
// import useSize from 'ahooks/es/useSize';
export default function VirtualScrolling(props) {
  const viewInfo = useMemo(() => {
    const { columnNum, rowNum, data, fixedRow, fixedColumn } = props;
    let x = data[0].length;
    let y = data.length;

    return {
      x,
      y,
      columnNum,
      rowNum,
      fixedRow,
      fixedColumn,
    };
  }, [props]);

  const [viewData, setViewData] = useState({
    fixedRow: [], //固定行
    fixedColumn: [], //固定列
    viewData: [], //数据
  });

  return (
    <div
      style={{
        height: '100%',
        width: '100%',
        position: 'relative',
      }}
    >
      <div
        style={{
          height: 'calc( 100% - 10px );',
          width: 'calc( 100% - 10px );',
          position: 'absolute',
        }}
      >
        {props.render(viewData.viewData, viewData.fixedRow, viewData.fixedColumn)}
      </div>
      <div
        onScroll={event => {
          var { scrollLeft, scrollTop } = event.target;
          const x = ~~scrollLeft;
          const y = ~~scrollTop;
          let viewData = [];
          let fixedRow = [];
          let fixedColumn = [];
          for (let vY = 0; vY < viewInfo.rowNum; vY++) {
            fixedColumn[vY] = props.data[y + vY][0];
            let xItem = [];
            for (let vX = 0; vX < viewInfo.columnNum; vX++) {
              xItem[vX] = props.data[y + vY][x + vX];
            }
            viewData[vY] = xItem;
          }
          for (let vX = 0; vX < viewInfo.columnNum; vX++) {
            fixedRow[vX] = props.data[0][x + vX];
          }
          setViewData({
            fixedRow, //固定行
            fixedColumn, //固定列
            viewData: viewData, //数据
          });
        }}
        style={{
          width: '100%',
          height: '100%',
          overflow: 'scroll',
        }}
      >
        {/* <div
          style={{
            height: viewInfo.height + 'px',
            width: viewInfo.width + 'px',
            position: 'absolute',
            alignContent: 'start',
            margin: '0px',
            display: 'flex',
            flexWrap: 'wrap',
            flexDirection: 'column',
          }}
        >
          {props.render(viewData.viewData, viewData.fixedRow, viewData.fixedColumn)}
        </div> */}
        <div
          style={{
            height: viewInfo.y + 'px',
            width: viewInfo.x + 'px',
          }}
        ></div>
      </div>
    </div>
  );
}

VirtualScrolling.defaultProps = {
  columnNum: 3, // 可视区域内数据列数
  rowNum: 5, // 可视区域内数据行数
  data: [], //数据
  noDataTips: '暂无数据', //自定义暂无数据提示
};
